#include <tT.h>
#include <env.h>

#include "transive.h"
#include "adc.h"
#include "can.h"
#include "hsadc.h"
#include "pid.h"


env_result_t transive_init(transive_t *self, void *none)
{
  ENV_DEBUG("enter transive_init()\r\n");
	TT_AFTER_BEFORE(10000000, 1000000, self, transive_send, TT_ARGS_NONE );
  //TT_AFTER_BEFORE(100000000, 1000, self, transive_send, TT_ARGS_NONE );
  //TT_AFTER_BEFORE(50000000, 1000, self, transive_send, TT_ARGS_NONE );
  //TT_AFTER_BEFORE(80000000, 1000, self, transive_send, TT_ARGS_NONE );
  
  return 0;
}

int val_send(int32_t val)
{
  if (val < 0 ) 
  {
    val = -val;
    ENV_DEBUG("-");
  }
  if ((val / 10) > 0) {
    adc_send(val / 10);
  }
  
  
    while ((UART1->FIFOLVL & (0xf << 8)) == (0xf << 8)) 
    {
			/* Busy wait for buffer space to become free. */
    }
    
    UART1->THR = (val%10) + '0';
    
    
  return 0;
}

env_result_t transive_send(transive_t *self, void *none)
{
	
  can_msg_t msg;
  msg.id = 0x100;		
  msg.len = 8; 
  msg.format = 0; 
  msg.type = 0;
  
  msg.data[0] = 0x01234567; //(adc.ad[0] & 0xFFFF) | (adc.ad[1]<<16);
  msg.data[1] = 0x89ABCDEF; //(adc.ad[2] & 0xFFFF) | (adc.ad[3]<<16);
  //can_send(&can, &msg);
  
  
  /*
  ENV_DEBUG("\r\n Temp = ");
  val_send(adc.ad[0]);
  ENV_DEBUG("  Volt = ");
  val_send(adc.ad[1]/7);
  ENV_DEBUG("  U+ = ");
  val_send(adc.ad[2]-4);
  ENV_DEBUG("  U- = ");
  val_send(adc.ad[3]-45);
  ENV_DEBUG("  V+ = ");
  val_send(adc.ad[4]-4);
  ENV_DEBUG("  V- = ");
  val_send(adc.ad[5]-3);
  ENV_DEBUG("  GND+ = ");
  val_send(adc.ad[6]-22);
  ENV_DEBUG("  GND- = ");
  val_send(adc.ad[7]);
  ENV_DEBUG("\r\n");
  ENV_DEBUG("\r\n");
	ENV_DEBUG("\r\n");
		
	ENV_DEBUG("HS ADC0 = ");
	val_send(hsadc.ad[0]);
	ENV_DEBUG("\r\n");
	ENV_DEBUG("HS ADC1 = ");
	*/	
	//val_send((hsadc.value[1]));
	//ENV_DEBUG("\r\n");
	
	val_send(pid.e/8);
	ENV_DEBUG("\r\n");

/*
  msg.id = 0x101;
  msg.data[0] = (adc.ad[4] & 0xFFFF) | (adc.ad[5]<<16);
  msg.data[1] = (adc.ad[6] & 0xFFFF) | (adc.ad[7]<<16);
  can_send(&can, &msg);
*/  
	TT_AFTER_BEFORE(100000000, 10000000, self, transive_send, TT_ARGS_NONE );
  return 0;
}

